<?php

namespace app\admin\model;

use app\common\model\TimeModel;

class StoragePath extends TimeModel
{


    public static $autoCache = [
        [
            'name' => 'full_path',
            'field' => 'path',
        ],
        [
            'name' => 'list_child_by_pid',
            'field' => 'pid'
        ],
        [
            'name' => 'list_recursive_child_by_path',
            'field' => 'path'
        ],
    ];

    protected $name = "storage_path";

    protected $deleteTime = "delete_time";


    public const SELECT_LIST_TYPE = ['node' => '文件', 'collection' => '目录',];

    public function getPropertiesAttr($value)
    {
        if (empty($value)) {
            return [];
        }

        return json_decode($value, true);
    }

    public function setPropertiesAttr($value)
    {
        return json_encode($value);
    }

    public function getPathNameAttr()
    {
        $path  = $this->getData('path');

        $path_arr = explode('/', $path);

        return end($path_arr);
    }

    public function getQuotaUsedBytesAttr()
    {
        $size = 0;
        if ($this->getAttr('type') == 'node') {
            $size += $this->getAttr('size');
        }

        if ($this->getAttr('type') == 'collection') {
            $list_path = StoragePath::where('pid', $this->getAttr('id'))
                ->autoCache('list_child_by_pid', $this->getAttr('id'))
                ->select();

            foreach ($list_path as  $model_path_item) {
                $size += $model_path_item->quota_used_bytes;
            }
        }

        return $size;
    }

    public function getStorageQuotaUsedBytesAttr()
    {

        if ($this->getAttr('type') == 'node') {
            return $this->getAttr('size');
        }

        return static::getStorageQuotaUsedBytes($this);
    }

    public static function getStorageQuotaUsedBytes($model_path)
    {
        $size = $model_path->size;

        if($model_path->type == 'collection'){

            $list_path = StoragePath::where('pid', $model_path->id)->select();
    
            foreach ($list_path as  $model_path_item) {
                $size += $model_path_item->quota_used_bytes;
            }
        }

        return $size;
    }
}
